package com.situ.blog.controller;



import com.situ.blog.pojo.entity.User;
import com.situ.blog.pojo.query.UserQuery;
import com.situ.blog.service.IUserService;
import com.situ.blog.service.impl.UserServiceImpl;
import com.situ.blog.util.JSONUtil;
import com.situ.blog.util.LayUITableResult;
import com.situ.blog.util.MD5Util;
import com.situ.blog.util.Result;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


@WebServlet("/user")
public class UserServlet extends HttpServlet {
    private IUserService userService = new UserServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //req.setCharacterEncoding("UTF-8");
        String method = req.getParameter("method");
        if (method == null || method.equals("")) {
            method = "selectByPage";
        }
        switch (method) {
            case "getUserListPage":
                getUserListPage(req, resp);
                break;
            case "selectByPage":
                selectByPage(req, resp);
                break;
            case "deleteById":
                deleteById(req, resp);
                break;
            case "deleteAll":
                deleteAll(req, resp);
                break;
            case "getUserAddPage":
                getUserAddPage(req, resp);
                break;
            case "add":
                add(req, resp);
                break;
            case "getLoginPage":
                getLoginPage(req, resp);
                break;
            case "login":
                login(req, resp);
                break;
            case "logout":
                logout(req, resp);
                break;
            case "updateStatus":
                updateStatus(req, resp);
                break;
        }
    }

    private void updateStatus(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("UserServlet.updateStatus");
        String id = req.getParameter("id");
        String status = req.getParameter("status");
        userService.updateStatus(Integer.parseInt(id), Integer.parseInt(status));

        JSONUtil.toJSON(resp, Result.ok("更新状态成功"));
    }

    private void logout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println("UserServlet.logout");
        HttpSession session = req.getSession();
        session.invalidate();
        resp.sendRedirect(req.getContextPath() + "/user?method=getLoginPage");
    }

    private void getLoginPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/WEB-INF/views/user/login.jsp").forward(req, resp);
    }

    private void login(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println("UserServlet.login");
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        String code = req.getParameter("code");

        HttpSession session = req.getSession();
        String codeInSession = (String) session.getAttribute("codeInSession");
        if (!codeInSession.equalsIgnoreCase(code)) {
            // {'code':1,'msg':'验证码错误'}
            Map<String, Object> map = new HashMap<>();
            map.put("code", 1);
            map.put("msg", "验证码错误");
            JSONUtil.toJSON(resp, map);
            return;
        }


        User user = userService.login(name, MD5Util.MD5Encode(password + MD5Util.SALT));
        if (user != null) {
            //该用户是否被禁用
            if (user.getStatus() == 0) {
                JSONUtil.toJSON(resp, Result.error("该用户被禁用"));
                return;
            }

            //把user作为登录凭证放到Session，
            //后面只要判断Session里面有没有user，就知道当前这个用户有没有登录
            session.setAttribute("user", user);
            JSONUtil.toJSON(resp, Result.ok("登录成功"));
        } else {
            JSONUtil.toJSON(resp, Result.error("用户名或密码错误"));
        }
    }

    private void getUserAddPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/WEB-INF/views/user/user_add.jsp").forward(req, resp);
    }

    private void add(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println("UserServlet.add");
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        String role = req.getParameter("role");
        String nickName = req.getParameter("nickName");
        String email = req.getParameter("email");
        String phone = req.getParameter("phone");
        String image = req.getParameter("image");
        User user = new User(name, password, Integer.parseInt(role),nickName, email, phone, image);
        userService.add(user);
        //resp.sendRedirect(req.getContextPath() + "/user");

        JSONUtil.toJSON(resp, Result.ok("添加成功"));
    }

    private void deleteById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println("UserServlet.deleteById");
        String id = req.getParameter("id");
        userService.deleteById(Integer.parseInt(id));
        //resp.sendRedirect(req.getContextPath() + "/user");

        JSONUtil.toJSON(resp, Result.ok("删除成功"));
    }

    private void deleteAll(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println("UserServlet.deleteAll");
        //String id = req.getParameter("id");
        String[] ids = req.getParameterValues("ids[]");
        userService.deleteAll(ids);

        JSONUtil.toJSON(resp, Result.ok("删除成功"));
    }

    private void getUserListPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/WEB-INF/views/user/user_list.jsp").forward(req, resp);
    }

    //http://localhost:8080/JavaWeb/user?method=selectByPage&page=1&limit=10
    private void selectByPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("UserServlet.selectByPage");
        String pageStr = req.getParameter("page");
        if (pageStr == null || pageStr.equals("")) {
            pageStr = "1";
        }
        String limitStr = req.getParameter("limit");
        if (limitStr == null || limitStr.equals("")) {
            limitStr = "10";
        }
        int page = Integer.parseInt(pageStr);
        int limit = Integer.parseInt(limitStr);
        String name = req.getParameter("name");
        String roleStr = req.getParameter("role");
        Integer role = StringUtils.isEmpty(roleStr) ? null : Integer.parseInt(roleStr);
        UserQuery userQuery = new UserQuery(page, limit, name, role);

        LayUITableResult layUITableResult = userService.selectByPage(userQuery);
        System.out.println("LayUITableResult: " + layUITableResult);

        JSONUtil.toJSON(resp, layUITableResult);
    }

}
